const net = require('net')
const fs = require('fs/promises')

// 创建一个TCP服务器
const server = net.createServer(() => {})

// 监听客户端连接事件
server.on('connection', async (socket) => {
  console.log('client connected', socket.remoteAddress)
  // read file
  let fileHandler, fileWriteStream
  
  // 监听客户端发送数据事件
  socket.on('data', async (data) => {
    // 如果文件句柄不存在，则打开文件
    if (!fileHandler) {
      socket.pause()

      const indexOfDivider = data.indexOf('------')
      const fileName = data.subarray(10, indexOfDivider).toString('utf-8')

      fileHandler = await fs.open(`storage/${fileName}`, 'w')
      fileWriteStream = fileHandler.createWriteStream()

      // 将数据写入文件
      fileWriteStream.write(data.subarray(indexOfDivider + 7))
      socket.resume()
      // 监听文件写入事件
      fileWriteStream.on('drain', () => {
        socket.resume()
      })
    } else {
      // 如果文件句柄存在，则将数据写入文件
      if (!fileWriteStream?.write(data)) {
        socket.pause()
      }
    }
  })

  // 监听客户端断开连接事件
  socket.on('end', async () => {
    console.log('client disconnected')
    // 关闭文件句柄
    fileHandler?.close()
    fileWriteStream?.close()
    fileHandler = null
    fileWriteStream = null
    socket.end()
  })
})

// 监听服务器启动事件
server.listen(5099, '::1', () => {
  console.log('server started', server.address())
})
